package com.zhang.homework.callable;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author zhang
 * @time 2022/02/16 20:42:25
 */
class T implements Callable<Integer> {
    private Random r = new Random();

    @Override
    public Integer call() throws Exception {

        int i = r.nextInt();
        System.out.println("子线程生成：" + i);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return i;
    }
}
public class Test {
    public static void main(String[] args) {
        T t = new T();

        ExecutorService es = Executors.newCachedThreadPool();
        Future<Integer> f = es.submit(t); // 不阻塞
        System.out.println("1111111111");
        Integer i = null;  // 会阻塞
        try {
            i = f.get(2000, TimeUnit.MILLISECONDS);
            System.out.println("22222222");
            System.out.println("主线程获取： " + i);
        } catch (TimeoutException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
            System.out.println("3333333");
        }
    }

}
